package cyvra;
import java.awt.Color;
import java.awt.Image;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;
/**
 *
 * @author CARDENASVAR
 */
public class frmLogeo extends javax.swing.JFrame {
    
    //Declaro variables de Conexion
    clsConnection oConn = new clsConnection();
    
    
     

    public frmLogeo() {
        
        //Intento Conexion
        if (! oConn.FnBoolConnetionOpen("com.mysql.jdbc.Driver", "jdbc:mysql://localhost/test","root","jonathan19"))
        {
            //No funciona una vez disponible
            // this.dispose();
            
            //Mensaje de que no logra conexion
            JOptionPane.showMessageDialog(null, "No se logro la conexion al Host");
            
            //Finaliza la Aplicacion
            System.exit(0);
        }
        else
        {
        
        initComponents();
        
            //carga imagen del icono
        Image icon = new ImageIcon(getClass().getResource("cyvra.png")).getImage();
        
        //coloca la imagen no es necesario this
        this.setIconImage(icon);
        
        
        
        // Inicia Minimizado
            this.setLocationRelativeTo(null);
            // Nombre del titulo
            this.setTitle("Acceso al Sistema CYVRA®");
            // Bloquea Maximizado
            this.setResizable(false);


            //Inicializa Controles
            lblUser.setText("Usuario:");
            lblPassword.setText("Contraseña:");
            txtUser.setText("");
            txpPassword.setText("");
            butCancel.setText("Cancelar");
            butAccept.setText("Aceptar");

            //Deshabilita los Despliegues
            lblName.setText("Nombre:");
            lblRole.setText("Cargo:");
            txtName.setEnabled(false);
            txtName.setBackground(Color.black);
            txtRole.setEnabled(false);
            txtRole.setBackground(Color.darkGray);
        }
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        pnlSession = new javax.swing.JPanel();
        lblUser = new javax.swing.JLabel();
        lblPassword = new javax.swing.JLabel();
        lblName = new javax.swing.JLabel();
        lblRole = new javax.swing.JLabel();
        txtUser = new javax.swing.JTextField();
        txtName = new javax.swing.JTextField();
        txtRole = new javax.swing.JTextField();
        txpPassword = new javax.swing.JPasswordField();
        butCancel = new javax.swing.JButton();
        butAccept = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        pnlSession.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));

        lblUser.setText("Usuario:");

        lblPassword.setText("Contraseña:");

        lblName.setText("Nombre:");

        lblRole.setText("Cargo:");

        javax.swing.GroupLayout pnlSessionLayout = new javax.swing.GroupLayout(pnlSession);
        pnlSession.setLayout(pnlSessionLayout);
        pnlSessionLayout.setHorizontalGroup(
            pnlSessionLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(pnlSessionLayout.createSequentialGroup()
                .addGap(37, 37, 37)
                .addGroup(pnlSessionLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(lblUser)
                    .addComponent(lblName)
                    .addComponent(lblRole)
                    .addComponent(lblPassword))
                .addGap(45, 45, 45)
                .addGroup(pnlSessionLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(txpPassword, javax.swing.GroupLayout.PREFERRED_SIZE, 210, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(txtUser, javax.swing.GroupLayout.PREFERRED_SIZE, 210, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(txtName, javax.swing.GroupLayout.PREFERRED_SIZE, 210, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(txtRole, javax.swing.GroupLayout.PREFERRED_SIZE, 210, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(45, Short.MAX_VALUE))
        );
        pnlSessionLayout.setVerticalGroup(
            pnlSessionLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(pnlSessionLayout.createSequentialGroup()
                .addGap(31, 31, 31)
                .addGroup(pnlSessionLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblUser)
                    .addComponent(txtUser, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(pnlSessionLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblPassword)
                    .addComponent(txpPassword, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(pnlSessionLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(lblName))
                .addGap(18, 18, 18)
                .addGroup(pnlSessionLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtRole, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(lblRole))
                .addContainerGap(24, Short.MAX_VALUE))
        );

        butCancel.setIcon(new javax.swing.ImageIcon(getClass().getResource("/iconos/cancel.png"))); // NOI18N
        butCancel.setText("Cancelar");
        butCancel.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                butCancelMouseClicked(evt);
            }
        });

        butAccept.setIcon(new javax.swing.ImageIcon(getClass().getResource("/iconos/accept.png"))); // NOI18N
        butAccept.setText("Aceptar");
        butAccept.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                butAcceptMouseClicked(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(23, 23, 23)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(butCancel)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(butAccept))
                    .addComponent(pnlSession, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(44, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(pnlSession, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(butCancel)
                    .addComponent(butAccept))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void butCancelMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_butCancelMouseClicked
        // TODO add your handling code here:
        oConn.SubConnectionClose();
        this.dispose();
    }//GEN-LAST:event_butCancelMouseClicked

    private void butAcceptMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_butAcceptMouseClicked
        // TODO add your handling code here:
        
        //Declaro Variable para Sentencia
        String sqlStmt;
        
        //Verifico que este Intentado Ingresar
        if (butAccept.getText() == "Aceptar")
        {
            if(FnBoolValidaDatos())
            {
                sqlStmt = "Select * from tblusers where strUserIde='"+txtUser.getText()+"' and strUserPass='"+String.valueOf(txpPassword.getPassword())+"'";
            
        
            //oConn.SubQueryExecute(sqlStmt);
        try
        {
            
            if (oConn.FnBoolQueryExecute(sqlStmt))
            {
                if (oConn.setResult.next())
                {
                txtName.setText(oConn.setResult.getString("strUserName"));
                txtRole.setText(oConn.setResult.getString("strRoleName"));
                
                butAccept.setText("Ingrese");
                butCancel.setEnabled(false);
                }
            else
            {
                txtName.setText("Usuario y/o Contraseña Incorrectos");
                txtRole.setText("Intente Nuevamente...");
            }
                
                oConn.setResult.close();
            } 
        } 
            
            catch (RuntimeException e)
            {
                JOptionPane.showMessageDialog(null, "Este Mensaje"+e);
            }
        
            catch (com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException e)
            {
                // Mensaje de que no logrola conexion
                JOptionPane.showMessageDialog(null,"Este Mensaje"+e);
            }
            catch (SQLException ex) 
            {                                
                Logger.getLogger(frmLogeo.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        
     }
        else
        {
         //JOptionPane.showMessageDialog(null, "Ingresando Al Sistema");
         //this.dispose();
            
            frmPrincipal frmprincipal = new frmPrincipal();
            //Vsible el form
            frmprincipal.setVisible(true);
            
            this.dispose();
        }
    }//GEN-LAST:event_butAcceptMouseClicked

    //Funcion para validar  datos de Captura
    private boolean FnBoolValidaDatos()
    {
        //Variables para el Mensaje
        String sMensaje="";
        
        //Valida el Usuario
        if (txtUser.getText().length()== 0)
        {
            //Añade el usuario al mensaje
            sMensaje ="Usuario";
            
            //Coloca el foco en el Objeto
            txtUser.requestFocus();
        }
        
        if (txpPassword.getPassword().length==0)
        {
            //Valida si no fallo con el usuario para mandar el foco
            if (sMensaje.length()== 0)
                //Mando el Foco al Password  si no ha fallado algun dato previo
                txpPassword.requestFocus();
            
                //Añade el usuario al Mensaje
            sMensaje = sMensaje+"\n"+"Password";
        }
        
        //Verifica si hay que desplegar  el mensaje
        if (sMensaje.length() > 0)
        {
            //Prepara el Mensaje
            sMensaje = "Debe capturar los siguientes datos:\n"+sMensaje;
            JOptionPane.showMessageDialog(null, sMensaje);
            
            //Devuelve falso
            return false;
        }
        else
        {
            //Retorna correcto
            return true;
        }
    
    }
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /*
         * Set the Nimbus look and feel
         */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel. For details see
         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(frmLogeo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(frmLogeo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(frmLogeo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(frmLogeo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /*
         * Create and display the form
         */
        java.awt.EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                new frmLogeo().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton butAccept;
    private javax.swing.JButton butCancel;
    private javax.swing.JLabel lblName;
    private javax.swing.JLabel lblPassword;
    private javax.swing.JLabel lblRole;
    private javax.swing.JLabel lblUser;
    private javax.swing.JPanel pnlSession;
    private javax.swing.JPasswordField txpPassword;
    private javax.swing.JTextField txtName;
    private javax.swing.JTextField txtRole;
    private javax.swing.JTextField txtUser;
    // End of variables declaration//GEN-END:variables
}
